<template>
  <div class="app-container policy-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px" class="search-form">
      <el-form-item label="文章标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入文章标题"
          clearable
          @keyup.enter.native="handleQuery"
          style="width: 240px;"
        />
      </el-form-item>
      <el-form-item label="作者/来源" prop="authorSource">
        <el-input
          v-model="queryParams.authorSource"
          placeholder="请输入作者来源"
          clearable
          @keyup.enter.native="handleQuery"
          style="width: 240px;"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete()">批量删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table 
      v-loading="loading" 
      :data="policyList" 
      @selection-change="handleSelectionChange"
      class="policy-table"
      :header-cell-style="{background:'#f5f7fa',color:'#606266',fontWeight:'600'}"
      stripe
      element-loading-text="数据加载中..."
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(255, 255, 255, 0.8)"
    >
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="序号" align="center" width="70">
        <template slot-scope="scope">
          {{ (queryParams.page - 1) * queryParams.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="文章标题" align="center" prop="title" min-width="180" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span class="title-text">{{ scope.row.title }}</span>
        </template>
      </el-table-column>
      <el-table-column label="作者/来源" align="center" prop="authorSource" min-width="120" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span class="author-text">{{ scope.row.authorSource }}</span>
        </template>
      </el-table-column>
      <el-table-column label="文章提要" align="center" prop="resume" min-width="200" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span class="summary-text">{{ scope.row.resume || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="正文内容" align="center" prop="content" min-width="200" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span class="content-text" v-html="getContentPreview(scope.row.content)"></span>
        </template>
      </el-table-column>
      <el-table-column label="发布时间" align="center" prop="publishTime" min-width="120">
        <template slot-scope="scope">
          <div class="time-wrapper">
            <i class="el-icon-time"></i>
            <span>{{ scope.row.publishTime || '-' }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="发布状态" align="center" prop="publishStatus" min-width="100">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.publishStatus === 1" type="success" size="small" effect="dark">
            <i class="el-icon-success"></i> 已发布
          </el-tag>
          <el-tag v-else type="info" size="small" effect="plain">
            <i class="el-icon-circle-close"></i> 未发布
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="是否推荐" align="center" prop="recommend" min-width="100">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.recommend === 1" type="danger" size="small" effect="dark">
            <i class="el-icon-star-on"></i> 推荐
          </el-tag>
          <el-tag v-else type="info" size="small" effect="plain">不推荐</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="浏览数量" align="center" prop="browseNum" min-width="100">
        <template slot-scope="scope">
          <span class="view-count">{{ scope.row.browseNum || 0 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="220" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button size="mini" type="text" @click="handleStatusChange(scope.row)" :class="{ 'active-text': scope.row.publishStatus !== 1 }">
            {{ scope.row.publishStatus === 1 ? '取消发布' : '发布' }}
          </el-button>
          <el-button size="mini" type="text" @click="handleRecommend(scope.row)" :class="{ 'active-text': scope.row.recommend !== 1 }">
            {{ scope.row.recommend === 1 ? '取消推荐' : '推荐' }}
          </el-button>
          <el-button size="mini" type="text" @click="handleDelete(scope.row)" style="color: #F56C6C;">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.page"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改补贴政策对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body @close="handleClose">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="文章标题" prop="title">
              <el-input v-model="form.title" placeholder="请输入文章标题" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="作者/来源" prop="authorSource">
              <el-input v-model="form.authorSource" placeholder="请输入作者/来源" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="文章摘要">
              <el-input v-model="form.summary" placeholder="请输入文章摘要" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="正文内容">
              <editor v-model="form.content" :min-height="300" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="发布时间" prop="publishTime">
              <el-date-picker
                v-model="form.publishTime"
                type="datetime"
                placeholder="请选择发布时间"
                format="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="发布状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择发布状态" style="width: 100%">
                <el-option label="已发布" :value="1" />
                <el-option label="未发布" :value="0" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="是否推荐" prop="isRecommend">
              <el-select v-model="form.isRecommend" placeholder="请选择是否推荐" style="width: 100%">
                <el-option label="推荐" :value="1" />
                <el-option label="不推荐" :value="0" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="浏览数量">
              <el-input-number v-model="form.viewCount" :min="0" placeholder="请输入浏览数量" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listPolicy, getPolicy, addPolicy, updatePolicy, delPolicy, exportPolicy, updatePolicyStatus, updatePolicyRecommend } from "@/api/yjnb/policy";
import Editor from "@/components/Editor";

export default {
  name: "Policy",
  components: {
    Editor
  },
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 补贴政策表格数据
      policyList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        page: 1,
        pageSize: 10,
        title: null,
        authorSource: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        title: [
          { required: true, message: "文章标题不能为空", trigger: "blur" }
        ],
        authorSource: [
          { required: true, message: "作者/来源不能为空", trigger: "blur" }
        ],
        publishTime: [
          { required: true, message: "发布时间不能为空", trigger: "change" }
        ],
        status: [
          { required: true, message: "发布状态不能为空", trigger: "change" }
        ],
        isRecommend: [
          { required: true, message: "是否推荐不能为空", trigger: "change" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询补贴政策列表 */
    getList() {
      this.loading = true;
      const params = { ...this.queryParams };
      
      listPolicy(params).then(response => {
        this.policyList = response.rows;
        this.total = response.total;
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },
    /** 获取内容预览 */
    getContentPreview(content) {
      if (!content) return '-';
      // 移除HTML标签，只保留文本
      const text = content.replace(/<[^>]+>/g, '');
      return text.length > 50 ? text.substring(0, 50) + '...' : text;
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: null,
        title: null,
        authorSource: null,
        summary: null,
        content: null,
        publishTime: null,
        status: 1,
        isRecommend: 0,
        viewCount: 0
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加补贴政策";
    },
    /** 弹窗关闭时重置表单 */
    handleClose() {
      this.reset();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids[0];
      getPolicy(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改补贴政策";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updatePolicy(this.form).then(response => {
              this.$message.success("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPolicy(this.form).then(response => {
              this.$message.success("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 单个修改发布状态 */
    handleStatusChange(row) {
      const status = row.publishStatus === 1 ? 0 : 1;
      const text = status === 1 ? '发布' : '取消发布';
      
      this.$confirm('是否确认' + text + '该补贴政策？', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        return updatePolicyStatus(row.id, status);
      }).then(() => {
        this.$message.success(text + '成功');
        this.getList();
      }).catch(() => {});
    },
    /** 单个推荐/取消推荐操作 */
    handleRecommend(row) {
      const isRecommend = row.recommend === 1 ? 0 : 1;
      const text = isRecommend === 1 ? '推荐' : '取消推荐';
      
      this.$confirm('是否确认' + text + '该补贴政策？', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        return updatePolicyRecommend(row.id, isRecommend);
      }).then(() => {
        this.$message.success(text + '成功');
        this.getList();
      }).catch(() => {});
    },
    /** 删除按钮操作（单个或批量） */
    handleDelete(row) {
      const isValidRow = row && row.id && row.title;
      const ids = isValidRow ? [row.id] : this.ids;
      
      if (!ids || ids.length === 0) {
        this.$message.warning('请选择要删除的补贴政策');
        return;
      }
      
      const message = isValidRow 
        ? `是否确认删除文章"${row.title}"？` 
        : `是否确认删除选中的${ids.length}条补贴政策？`;
      
      this.$confirm(message, "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        return delPolicy(ids);
      }).then(() => {
        this.$message.success('删除成功');
        this.getList();
      }).catch(() => {});
    },
    /** 导出补贴政策数据 */
    handleExport() {
      this.loading = true;
      exportPolicy().then(response => {
        this.loading = false;
        // 创建Blob对象
        const blob = new Blob([response], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
        // 创建下载链接
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        // 设置文件名
        const fileName = `补贴政策数据_${new Date().getTime()}.xlsx`;
        link.download = fileName;
        // 触发下载
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        URL.revokeObjectURL(link.href);
        this.$message.success('导出成功');
      }).catch(() => {
        this.loading = false;
        this.$message.error('导出失败，请重试');
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.policy-container {
  background: #f0f2f5;

  /* 搜索表单样式 */
  .search-form {
    background: #fff;
    padding: 18px 16px 6px;
    border-radius: 8px;
    margin-bottom: 16px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
    
    ::v-deep .el-form-item {
      margin-bottom: 12px;
    }
  }

  /* 按钮行样式 */
  .mb8 {
    background: #fff;
    padding: 12px 16px;
    border-radius: 8px;
    margin-bottom: 16px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  }

  /* 表格容器样式 */
  .policy-table {
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
    overflow: hidden;

    /* 文章标题样式 */
    .title-text {
      color: #303133;
      font-weight: 600;
      font-size: 14px;
      cursor: pointer;
      transition: color 0.3s;

      &:hover {
        color: #409EFF;
      }
    }

    /* 作者样式 */
    .author-text {
      color: #606266;
      font-size: 13px;
    }

    /* 摘要样式 */
    .summary-text {
      color: #909399;
      font-size: 13px;
    }

    /* 内容样式 */
    .content-text {
      color: #606266;
      font-size: 13px;
    }

    /* 浏览数量样式 */
    .view-count {
      color: #909399;
      font-size: 13px;
    }

    /* 时间样式 */
    .time-wrapper {
      color: #909399;
      font-size: 13px;

      i {
        margin-right: 4px;
        color: #C0C4CC;
      }
    }

    /* 表格行悬停效果 */
    ::v-deep .el-table__row {
      transition: all 0.3s ease;
      
      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
      }
    }
    
    /* 操作按钮样式 */
    .active-text {
      color: #409EFF;
    }
  }

  /* 分页样式 */
  ::v-deep .pagination-container {
    margin-top: 16px;
    background: #fff;
    padding: 16px;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  }
}
</style>
